#include "LogManager.h"
#include "DatabaseManager.h" // 确保包含 DatabaseManager 的头文件
#include <iostream>
#include <fstream>

using namespace std;

// 静态实例初始化
LogManager& LogManager::getInstance() {
    static LogManager instance;
    return instance;
}

// 构造函数
LogManager::LogManager() {
    // 初始化代码
}

LogManager::~LogManager() {
    // 析构函数实现
}

// 记录日志
void LogManager::logAction(Log::LogType logType, int userId, int deviceId, const string& content) {
    lock_guard<mutex> lock(logMutex); // 确保线程安全
    logs.emplace_back(logType, userId, deviceId, content);

    // 获取数据库管理器实例
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    // 构造插入语句
    string insertQuery = "INSERT INTO logs (log_type, timestamp, user_id, device_id, log_content) VALUES ('" 
                         + to_string(static_cast<int>(logType)) + "', CURRENT_TIMESTAMP, " + to_string(userId) + ", " + to_string(deviceId) + ", '" + content + "');";
    // 执行插入语句
    if (!dbManager.executeQuery(insertQuery)) {
        //cout << "日志记录成功" << endl;
        cerr << "错误：日志记录失败" << endl;
    }
}

// 保存日志到文件
void LogManager::saveLogsToFile(const string& filename) {
    ofstream file(filename);
    if (file.is_open()) {
        for (const auto& log : logs) {
            file << "日志类型: " << static_cast<int>(log.getLogType())
                 << ", 用户 ID: " << log.getUserId()
                 << ", 设备 ID: " << log.getDeviceId()
                 << ", 内容: " << log.getContent() << endl;
        }
        file.close();
        cout << "日志已保存到文件: " << filename << endl;
    } else {
        cerr << "错误：无法打开文件" << endl;
    }
}

// 获取用户日志
vector<Log> LogManager::getLogsByUser(int userId) const {
    vector<Log> userLogs;
    for (const auto& log : logs) {
        if (log.getUserId() == userId) {
            userLogs.push_back(log);
        }
    }
    return userLogs;
}

// 获取设备日志
vector<Log> LogManager::getLogsByDevice(int deviceId) const {
    vector<Log> deviceLogs;
    for (const auto& log : logs) {
        if (log.getDeviceId() == deviceId) {
            deviceLogs.push_back(log);
        }
    }
    return deviceLogs;
}
